import requests
import csv

# GitLab API 配置
GITLAB_URL = "http://gitlab.cowain.com.cn"  # GitLab 服务器地址
PRIVATE_TOKEN = "glpat-2ib_W5abre6FrXiy856y"  # GitLab 私人令牌

# API 请求头
HEADERS = {
    "PRIVATE-TOKEN": PRIVATE_TOKEN
}

# 权限级别映射表
ACCESS_LEVEL_MAPPING = {
    10: "Guest",
    20: "Reporter",
    30: "Developer",
    40: "Maintainer",
    50: "Owner"
}

def get_all_projects():
    """
    获取 GitLab 上的所有项目
    """
    projects = []
    page = 1
    while True:
        url = f"{GITLAB_URL}/api/v4/projects?per_page=100&page={page}"
        response = requests.get(url, headers=HEADERS)
        if response.status_code != 200:
            print(f"获取项目失败：{response.status_code}, {response.text}")
            break
        data = response.json()
        if not data:
            break
        projects.extend(data)
        page += 1
    return projects

def get_project_members(project_id):
    """
    获取某个项目的成员信息
    """
    members = []
    page = 1
    while True:
        url = f"{GITLAB_URL}/api/v4/projects/{project_id}/members/all?per_page=100&page={page}"
        response = requests.get(url, headers=HEADERS)
        if response.status_code != 200:
            print(f"获取项目 {project_id} 成员失败：{response.status_code}, {response.text}")
            break
        data = response.json()
        if not data:
            break
        members.extend(data)
        page += 1
    return members

def export_to_csv(projects_with_members, output_file="gitlab_projects_members.csv"):
    """
    导出项目和成员数据到 CSV
    """
    with open(output_file, mode="w", encoding="utf-8", newline="") as file:
        writer = csv.writer(file)
        # 写入表头
        writer.writerow(["Project ID", "Project Name", "Member ID", "Username", "Name", "Access Level"])
        # 写入数据
        for project in projects_with_members:
            project_id = project["id"]
            project_name = project["name"]
            for member in project["members"]:
                access_level_name = ACCESS_LEVEL_MAPPING.get(member["access_level"], "Unknown")
                writer.writerow([
                    project_id,
                    project_name,
                    member["id"],
                    member["username"],
                    member["name"],
                    access_level_name
                ])
    print(f"数据已导出到 {output_file}")

def main():
    print("开始获取所有项目...")
    projects = get_all_projects()
    print(f"共获取到 {len(projects)} 个项目。")

    projects_with_members = []
    for project in projects:
        print(f"获取项目 {project['id']} 的成员...")
        members = get_project_members(project["id"])
        projects_with_members.append({
            "id": project["id"],
            "name": project["name"],
            "members": members
        })

    print("开始导出数据到 CSV...")
    export_to_csv(projects_with_members)

if __name__ == "__main__":
    main()

